package models

import (
	"fmt"
	"time"

	"github.com/go-redis/redis"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

const redisPrefix = "integral_api:"

var Rds *redis.Client
var Db *gorm.DB

func init() {
	//initializing redis client 初始化redis客户端
	redisAddr, redisPassword := viper.GetString("settings.redis.addr"), viper.GetString("settings.redis.password")
	if redisAddr != "" {
		Rds = redis.NewClient(&redis.Options{
			Addr:     redisAddr,
			Password: redisPassword,                     // no password set
			DB:       viper.GetInt("settings.redis.db"), // use default DB
		})
		if pong, err := Rds.Ping().Result(); err != nil || pong != "PONG" {
			logrus.WithError(err).Fatal("could not connect to the redis server")
		}
	}

	//init mysql 初始化mysql
	conn := fmt.Sprintf("%s:%s@(%s)/%s?charset=%s&parseTime=True&loc=Local", viper.GetString("settings.database.username"),
		viper.GetString("settings.database.password"), viper.GetString("settings.database.host")+":"+viper.GetString("settings.database.port"),
		viper.GetString("settings.database.database"), "utf8")
	if db, err := gorm.Open("mysql", conn); err == nil {
		// 超过30秒就timeout
		db.DB().SetConnMaxLifetime(time.Second * 30)

		Db = db
	} else {
		logrus.WithError(err).Fatalln("initialize mysql database failed")
	}

	//init

}

// 关闭操作
func Close() {
	if Db != nil {
		err := Db.Close()
		if err != nil {
			logrus.WithError(err).Fatalln("close mysql database failed")
		}
	}
	if Rds != nil {
		err := Rds.Close()
		if err != nil {
			logrus.WithError(err).Fatalln("close redis database failed")
		}
	}
}
